import React, { useEffect, useState } from "react";
import { Button, Form, InputNumber, Modal, Spin, Table } from "antd";
import { SidebarStaff } from "../../../components/Sidebar";
import "./index.less";
import { ClearPair, GetPairList, Pairing } from "../../../api";
import { useNavigate, useParams } from "react-router-dom";
import { IPairing } from "../../../utils/constant";

const columns = [
  {
    title: "Reviewee ID",
    dataIndex: "studentId",
    key: "studentId",
    width: 200,
  },
  {
    title: "Reviewer ID",
    dataIndex: "markerId",
    key: "markerId",
    width: 200,
  },
];

const Index: React.FC = () => {
  const params = useParams();
  const [pairList, setPairList] = useState<IPairing[]>([]);
  const assignmentId = +params.assignmentId!;
  const moduleId = +params.id!;
  const [isPairModalOpen, setIsPairModalOpen] = useState<boolean>(false);
  const [isPairing, setIsPairing] = useState<boolean>(false);
  const [pairSize, setPairSize] = useState<number>(1);

  const navigate = useNavigate();

  const openPairModal = () => {
    setIsPairModalOpen(true);
  };
  const closePairModal = () => {
    setIsPairModalOpen(false);
  };

  const handlePairSizeChange = (size: number | null) => {
    setPairSize(size || 0);
  };

  const handlePair = async () => {
    setIsPairing(true);
    try {
      await Pairing({
        moduleId,
        assignmentId,
        pairSize,
      });
      closePairModal();
      await fetchPairList();
      setIsPairing(false);
    } catch (e) {
      console.error(e);
      setIsPairing(false);
    }
  };

  const deleteConfirm = () => {
    Modal.confirm({
      title: "Are you sure to Clear?",
      okText: "Yes",
      cancelText: "Cancel",
      onOk: handleClearPair,
    });
  };

  const handleClearPair = async () => {
    try {
      const ids = pairList.map((item) => item.id);
      await ClearPair({ ids });
      await fetchPairList();
    } catch (e) {
      console.error(e);
    }
  };

  const fetchPairList = async () => {
    try {
      const {
        data: { data },
      } = await GetPairList(assignmentId);
      setPairList(data);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    fetchPairList();
  }, []);
  return (
    <>
      <SidebarStaff></SidebarStaff>
      <div className="pair-list">
        <div className="pair-list-header">
          {pairList.length === 0 ? (
            <Button onClick={openPairModal}>Pair</Button>
          ) : (
            <>
            <Button onClick={deleteConfirm}>Clear</Button>
            <Button onClick={() => navigate(`/staff/module/${moduleId}/assignments/${assignmentId}/participation`)}>View Participation</Button>
            </>
          )}
        </div>

        <Table
          dataSource={pairList}
          columns={columns}
          className="pair-list-table"
        ></Table>
      </div>
      <Modal
        title="Pair Size"
        open={isPairModalOpen}
        onOk={handlePair}
        onCancel={closePairModal}
      >
        <Form>
          <Form.Item label="PariSize">
            <InputNumber
              onChange={handlePairSizeChange}
              defaultValue={1}
              min={1}
            ></InputNumber>
          </Form.Item>
        </Form>
      </Modal>
      <Spin
        className="pair-loading"
        spinning={isPairing}
        tip="Pairing..."
        size="large"
      >
        <div className="content"></div>
      </Spin>
    </>
  );
};

export default Index;
